<template>
  <el-dialog
    v-el-drag-dialog
    :title="type === 'add' ? '新增仓库信息' : '编辑仓库信息'"
    :visible.sync="visible"
    width="500px"
    @closed="reset"
  >
    <el-form ref="dataForm" class="form" :rules="rules" :model="temp" label-position="right" label-width="85px">
      <!-- <el-form-item label="仓库编码" prop="storeCode">
        <el-input v-model.trim="temp.storeCode" :maxlength="11" :disabled="type === 'edit'" :style="type === 'add' ? 'width: 275px' : null" clearable />
        <el-button v-if="type === 'add'" type="primary" size="small" plain @click.prevent="getCode">获取</el-button>
      </el-form-item> -->
      <el-form-item label="关联类型" prop="reType">
        <el-select v-model="temp.reType" placeholder="请选择" :disabled="type === 'edit'" style="width: 100%;" @change="reTypeChange">
          <el-option
            v-for="item in reTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="temp.reType === 1" label="关联机构" prop="reId">
        <el-tree-select
          v-model="temp.reId"
          :disabled="type === 'edit'"
          class="tree-select"
          clearable
          :select-params="{
            placeholder: '请选择'
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgId',
              label: 'orgName',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
          @select-clear="closeTree"
        />
      </el-form-item>
      <el-form-item v-if="temp.reType === 2" label="配送员" prop="reId">
        <el-select v-if="type==='add'" v-model="temp.reId" filterable :loading="$loadingPlugin.getOwnerList" style="width: 100%;" placeholder="请选择" @change="delivermanChange">
          <el-option
            v-for="item in delivermanList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
        <el-input v-else v-model="temp.rName" disabled />
      </el-form-item>
      <el-form-item v-if="temp.reType === 3" label="关联机构" prop="reId">
        <el-tree-select
          v-model="temp.reId"
          :disabled="type === 'edit'"
          class="tree-select"
          :select-params="{
            clearable: false,
            placeholder: '请选择'
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgId',
              label: 'orgName',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
          @select-clear="closeTree"
        />
      </el-form-item>
      <el-form-item v-if="temp.reType === 6" label="其他" prop="reId">
        <el-tree-select
          v-model="temp.reId"
          :disabled="type === 'edit'"
          class="tree-select"
          :select-params="{
            clearable: false,
            placeholder: '请选择'
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgId',
              label: 'orgName',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
          @select-clear="closeTree"
        />
      </el-form-item>
      <el-form-item label="仓库名称" prop="storeName">
        <el-input v-model.trim="temp.storeName" clearable placeholder="请输入" maxlength="20" />
      </el-form-item>
      <el-form-item label="仓库主管" prop="directorId">
        <el-select v-model="temp.directorId" :loading="$loadingPlugin.getOwnerList" style="width: 100%;" placeholder="请选择" @change="directorIdChange">
          <el-option
            v-for="item in ownerList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="联系电话">
        <el-input v-model="temp.directorTel" maxlength="11" @input="temp.directorTel = temp.directorTel.replace(/[^\d]/g, '')" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        关闭
      </el-button>
      <el-button :loading="$loadingPlugin.add || $loadingPlugin.edit" type="primary" @click="success">
        保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { warehouseAdd, queryOrgCode, queryOwnerList, queryDelivermanList } from '@/api'
  import { mapGetters } from 'vuex'
  import getTreeData from '@/utils/jsonTree'
  // import { isWildPhone } from '@/utils'

  export default {
    name: 'add',
    props: {
      reTypeMap: {
        type: Array,
        required: true
      }
    },
    data() {
      // const validateTruckCode = (rule, value, callback) => {
      //   if (value !== '') {
      //     if (!isWildPhone(value)) {
      //       callback(new Error('联系电话格式输入不正确，请重新输入'))
      //     }
      //   } else {
      //     callback()
      //   }
      //   callback()
      // }
      return {
        visible: false,
        type: 'add',
        currentOrg: null,
        treeData: [],
        storeTreeData: [], // 门市下拉数据
        ownerList: [], // 主管
        delivermanList: [], // 配送员
        temp: {
          storeCode: '',
          storeName: '',
          reType: 1,
          reId: '',
          directorTel: '',
          directorId: ''
        },
        rules: {
          storeName: [{ required: true, message: '请输入仓库名称', trigger: 'change' }],
          reType: [{ required: true, message: '请选择关联类型', trigger: 'change' }],
          reId: [{ required: true, message: `请选择`, trigger: 'change' }]
          // directorId: [{ required: true, message: '请选择主管', trigger: 'blur' }],
          // directorTel: [{ required: true, message: '请输入手机号', trigger: 'blur' }]
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'corpSettingData'
      ]),
      reTypeLabel: function() {
        let label = ''
        switch (this.temp.reType) {
        case 1:
          label = '门市'
          break
        case 2:
          label = '配送员'
          break
        case 3:
          label = '气站'
          break
        case 6:
          label = '其他'
          break
        }
        return label
      }
    },
    methods: {
      open(temp) {
        this.getTreeData()
        this.filterData(1)
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          if (temp) {
            this.temp = Object.assign(this.temp, temp)
            if (!temp.directorId) this.temp.directorId = ''
            this.type = 'edit'
            this.getOwnerList(temp.reId)
          }
        })
      },
      // 获取仓库编码
      async getCode() {
        const res = await queryOrgCode({
          codeType: 4
        })
        this.temp.storeCode = res.data
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 获取主管列表
      async getOwnerList(orgId) {
        const b = this.corpSettingData.sp1 >> 2 & 0x01
        const res = await queryOwnerList({
          orgId,
          corpparm1: b
        })
        this.ownerList = res.data.filter(item => (item.utype >> 2 & 0x01) > 0)
        if (res.data.length === 0 && this.temp.directorId) {
          this.ownerList = [{
            userName: this.temp.director,
            userId: this.temp.directorId
          }]
        }
        if (!this.temp.directorId) {
          if (this.ownerList.length) {
            this.$set(this.temp, 'directorId', this.ownerList[0].userId)
            this.$set(this.temp, 'directorTel', this.ownerList[0].uphone)
          }
        } else {
          const match = this.ownerList.find(item => item.userId === this.temp.directorId)
          if (!match) this.temp.directorId = ''
        }
        this.delivermanList = res.data
      },
      // 选择所属机构
      selectTreeChange(value) {
        console.log(value)
        this.currentOrg = value
        this.$set(this.temp, 'storeName', value.orgName)
        this.$set(this.temp, 'directorTel', '')
        this.$set(this.temp, 'directorId', '')
        this.getOwnerList(value.orgId)
      },
      closeTree(v) {
        this.$set(this.temp, 'reId', '')
        this.$set(this.temp, 'storeName', '')
        this.$set(this.temp, 'directorTel', '')
        this.$set(this.temp, 'directorId', '')
        this.ownerList = []
        this.delivermanList = []
      },
      // 关联类型变化
      async reTypeChange(type) {
        if (type === 2) {
          const res = await queryDelivermanList()
          this.delivermanList = res.data
        }
        this.ownerList = []
        this.$set(this.temp, 'reId', '')
        this.$set(this.temp, 'storeName', '')
        this.$set(this.temp, 'directorTel', '')
        this.$set(this.temp, 'directorId', '')
        this.filterData(type)
      },
      directorIdChange(value) {
        const match = this.ownerList.find(item => item.userId === value)
        this.$set(this.temp, 'directorTel', match.uphone)
      },
      filterData(type) {
        // const dre = (this.corpSettingData.sp1 >> 1 & 0x01) ? 0 : -1
        const dre = 0
        // console.log(dre)
        if (type === 1) this.getOrgCache(dre, 11, type)
        else if (type === 3) this.getOrgCache(dre, 7, type)
      },
      getOrgCache(dre, t, type) {
        const tempdatas = []
        for (let i = 0; i < this.orgList.length; i++) {
          const item = this.orgList[i]
          if (item.orgType === t) {
            if (dre) {
              tempdatas.push(item)
              continue
            }
            tempdatas.push({ ...item })
          }
        }
        console.log(tempdatas)
        this.treeData = tempdatas
      },
      // 配送员变化
      async delivermanChange(value) {
        this.$set(this.temp, 'directorId', '')
        this.$set(this.temp, 'directorTel', '')
        const match = this.delivermanList.find(item => item.userId === value)
        this.ownerList = this.delivermanList.filter(item => item.userId === value)
        this.$set(this.temp, 'directorId', value)
        if (match) this.$set(this.temp, 'directorTel', match.uphone)
      },
      success() {
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          this.$confirm(`确认保存仓库信息？`, '提示', {
            type: 'info'
          }).then(() => {
            let match = {}
            if (this.temp.directorId) {
              match = this.ownerList.find(item => item.userId === this.temp.directorId)
            }
            const params = {
              storeName: this.temp.storeName,
              reType: this.temp.reType,
              directorId: this.temp.directorId,
              director: match.userName || '',
              directorTel: this.temp.directorTel,
              reId: this.temp.reId
            }
            if (this.temp.reType === 2) {
              const deliverman = this.delivermanList.find(item => item.userId === this.temp.reId)
              if (deliverman) params.rName = deliverman.userName
            } else {
              const org = this.orgList.find(item => item.orgId === this.temp.reId)
              if (org) params.rName = org.orgName
            }
            if (this.type === 'add') {
              params.storeCode = this.temp.storeCode
              this.add(params)
            } else {
              params.storeId = this.temp.storeId
              this.add(params)
            }
          })
        })
      },
      async add(params) {
        await warehouseAdd(params)
        this.resolve()
        this.visible = false
        this.$notify({
          title: '提示',
          message: '仓库信息保存成功',
          type: 'success',
          duration: 2000
        })
      },
      reset() {
        this.type = 'add'
        this.temp = {
          storeCode: '',
          storeName: '',
          reType: 1,
          reId: '',
          directorTel: '',
          directorId: ''
        }
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>

</style>
